package cn.dxl.springcloudgateway.config;


import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class KeyResolverConfig {



    /***
     * 只能有一个KeyResolver 多个会报错 。
     */


    /**
     * 编写基于请求路径的限流规则
     */
    @Bean("pathKeyResolver")
    public KeyResolver pathKeyResolver(){
        return new KeyResolver() {
            /**
             * ServerWebExchange 核心类
             * @param exchange
             * @return
             */
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                //根据路径限流
                return Mono.just(exchange.getRequest().getPath().toString());
            }
        };
    }

    /**
     * 比如说根据某一个参数去限流 我这边设定的参数为有userId的接口
     * @return
     */
//    @Bean("ParamKeyResolver")
    public KeyResolver ParamKeyResolver(){
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
    }



    /**
     * 根据IP限流
     *
     * X-Forwarded-For 浏览器参数 获取每次请求浏览器携带的ip
     * @return
     */
//    @Bean("IpKeyResolver")
    public KeyResolver IpKeyResolver(){
        return exchange -> Mono.just(exchange.getRequest().getHeaders().getFirst("X-Forwarded-For"));
    }
}
